<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="crossoverJie, Java" />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="You never know what you can do till you try.">
<meta property="og:type" content="website">
<meta property="og:title" content="crossoverJie's Blog">
<meta property="og:url" content="http://crossoverjie.top/page/7/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="You never know what you can do till you try.">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="crossoverJie's Blog">
<meta name="twitter:description" content="You never know what you can do till you try.">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/page/7/"/>

  <title> crossoverJie, Java - crossoverJie's Blog - You never know what you can do till you try. </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/06/13/guava/guava-cache/" itemprop="url">
                  Guava 源码分析（Cache 原理）
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-06-13T01:20:42+08:00" content="2018-06-13">
              2018-06-13
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Guava/" itemprop="url" rel="index">
                    <span itemprop="name">Guava</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/06/13/guava/guava-cache/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/06/13/guava/guava-cache/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/06/13/guava/guava-cache/" class="leancloud_visitors" data-flag-title="Guava 源码分析（Cache 原理）">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2018/06/12/5b1fea79e07cb.jpeg" alt="1.jpeg"></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>Google 出的 <a href="https://github.com/google/guava">Guava</a> 是 Java 核心增强的库，应用非常广泛。</p>
<p>我平时用的也挺频繁，这次就借助日常使用的 Cache 组件来看看 Google 大牛们是如何设计的。</p>
<h2 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h2><blockquote>
<p>本次主要讨论缓存。</p>
</blockquote>
<p>缓存在日常开发中举足轻重，如果你的应用对某类数据有着较高的读取频次，并且改动较小时那就非常适合利用缓存来提高性能。</p>
<p>缓存之所以可以提高性能是因为它的读取效率很高，就像是 CPU 的 <code>L1、L2、L3</code> 缓存一样，级别越高相应的读取速度也会越快。</p>
<p>但也不是什么好处都占，读取速度快了但是它的内存更小资源更宝贵，所以我们应当缓存真正需要的数据。</p>
<blockquote>
<p>其实也就是典型的空间换时间。</p>
</blockquote>
<p>下面谈谈 Java 中所用到的缓存。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/06/13/guava/guava-cache/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/06/07/distributed-lock/distributed-lock-redis-update/" itemprop="url">
                  分布式工具的一次小升级⏫
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-06-07T22:20:46+08:00" content="2018-06-07">
              2018-06-07
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Distributed-Tools/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed Tools</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/06/07/distributed-lock/distributed-lock-redis-update/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/06/07/distributed-lock/distributed-lock-redis-update/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/06/07/distributed-lock/distributed-lock-redis-update/" class="leancloud_visitors" data-flag-title="分布式工具的一次小升级⏫">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2019/05/08/5cd1d53277e6e.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>之前在做 <a href="https://crossoverjie.top/2018/05/07/ssm/SSM18-seconds-kill/#distributed-redis-tool-%E2%AC%86%EF%B8%8Fv1-0-3">秒杀架构实践</a> 时有提到对 <a href="https://github.com/crossoverJie/distributed-redis-tool">distributed-redis-tool</a> 的一次小升级，但是没有细说。</p>
<p>其实主要原因是：</p>
<blockquote>
<p>秒杀时我做压测：由于集成了这个限流组件，并发又比较大，所以导致连接、断开 Redis 非常频繁。<br>最终导致获取不了 Redis connection 的异常。</p>
</blockquote>
<h2 id="池化技术"><a href="#池化技术" class="headerlink" title="池化技术"></a>池化技术</h2><p>这就是一个典型的对稀缺资源使用不善导致的。</p>
<p>何为稀缺资源？常见的有：</p>
<ul>
<li>线程</li>
<li>数据库连接</li>
<li>网络连接等</li>
</ul>
<p>这些资源都有共同的特点：<strong>创建销毁成本较高</strong>。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/06/07/distributed-lock/distributed-lock-redis-update/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/06/06/exam/2018-06-07-The-university-entrance-exam/" itemprop="url">
                  记于 2018 年高考！
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-06-06T22:20:46+08:00" content="2018-06-06">
              2018-06-06
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/小情绪/" itemprop="url" rel="index">
                    <span itemprop="name">小情绪</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/06/06/exam/2018-06-07-The-university-entrance-exam/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/06/06/exam/2018-06-07-The-university-entrance-exam/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/06/06/exam/2018-06-07-The-university-entrance-exam/" class="leancloud_visitors" data-flag-title="记于 2018 年高考！">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <h2 id="2012-02-28"><a href="#2012-02-28" class="headerlink" title="2012/02/28"></a>2012/02/28</h2><p><img src="https://i.loli.net/2019/05/08/5cd1d5256dfa7.jpg" alt=""></p>
<blockquote>
<p>2012年二月二十八日。</p>
</blockquote>
<p>这天学校举行了<code>高考 100 天誓师大会</code>，当时完全不知道意味着什么，只感觉现场热血沸腾、激情高涨，心里告诉自己就算只剩下 100 天我也能考上清华其次也是北大。</p>
<h2 id="2012-06-03"><a href="#2012-06-03" class="headerlink" title="2012/06/03"></a>2012/06/03</h2><blockquote>
<p>2012年六月三日。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/05/08/5cd1d528366b0.jpg" alt=""></p>
<p>晚自习拿出前段时间刚拍的毕业合照，恨死摄影师，没有抓拍到我最帅的角度😡。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/06/06/exam/2018-06-07-The-university-entrance-exam/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/05/24/netty/Netty(1)TCP-Heartbeat/" itemprop="url">
                  Netty(一) SpringBoot 整合长连接心跳机制
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-05-24T01:02:54+08:00" content="2018-05-24">
              2018-05-24
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/" itemprop="url" rel="index">
                    <span itemprop="name">Netty</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/05/24/netty/Netty(1)TCP-Heartbeat/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/05/24/netty/Netty(1)TCP-Heartbeat/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/05/24/netty/Netty(1)TCP-Heartbeat/" class="leancloud_visitors" data-flag-title="Netty(一) SpringBoot 整合长连接心跳机制">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2018/05/25/5b0774828db53.jpeg" alt="photo-1522204657746-fccce0824cfd.jpeg"></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Netty 是一个高性能的 NIO 网络框架，本文基于 SpringBoot 以常见的心跳机制来认识 Netty。</p>
<p>最终能达到的效果：</p>
<ul>
<li>客户端每隔 N 秒检测是否需要发送心跳。</li>
<li>服务端也每隔 N 秒检测是否需要发送心跳。</li>
<li>服务端可以主动 push 消息到客户端。</li>
<li>基于 SpringBoot 监控，可以查看实时连接以及各种应用信息。</li>
</ul>
<p>效果如下：</p>
<p><img src="https://crossoverjie.top/uploads/netty-Heartbeat.gif" alt="show"></p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/05/24/netty/Netty(1)TCP-Heartbeat/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/05/15/skill/1Kstar/" itemprop="url">
                  1K star+ 的项目是如何炼成的？
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-05-15T01:00:44+08:00" content="2018-05-15">
              2018-05-15
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/小技巧/" itemprop="url" rel="index">
                    <span itemprop="name">小技巧</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/05/15/skill/1Kstar/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/05/15/skill/1Kstar/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/05/15/skill/1Kstar/" class="leancloud_visitors" data-flag-title="1K star+ 的项目是如何炼成的？">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2018/05/14/5af935ddc27e1.jpg" alt="alarm-clock-art-background-1037993.jpg"></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>首先标题党一下，其实这篇文章主要是记录我的第二个过 <code>1K star</code> 的项目 <a href="https://github.com/crossoverJie/Java-Interview">Java-Interview</a>，顺便分享下其中的过程及经验。</p>
<p><img src="https://i.loli.net/2018/05/15/5af9b89e8bff8.png" alt="4.png"></p>
<h1 id="需求选择"><a href="#需求选择" class="headerlink" title="需求选择"></a>需求选择</h1><h2 id="Java-Interview"><a href="#Java-Interview" class="headerlink" title="Java-Interview"></a><a href="https://github.com/crossoverJie/Java-Interview">Java-Interview</a></h2><p>之所以要做这个项目主要是当时我正在面阿里的两个部门，非常幸运的是技术面都过了。其中的过程真是让我受益匪浅更是印象深刻，所以就想把期间的问题记录下来，加上自己的理解希望能对其他朋友起到帮助。</p>
<p>正好那段时间也是传说中的<code>金三银四</code>，所以无形中也叫顺势而为吧😏。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/05/15/skill/1Kstar/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/05/07/ssm/SSM18-seconds-kill/" itemprop="url">
                  SSM(十八) 秒杀架构实践
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-05-07T01:12:54+08:00" content="2018-05-07">
              2018-05-07
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/SSM/" itemprop="url" rel="index">
                    <span itemprop="name">SSM</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/SSM/Distributed-Tools/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed Tools</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/05/07/ssm/SSM18-seconds-kill/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/05/07/ssm/SSM18-seconds-kill/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/05/07/ssm/SSM18-seconds-kill/" class="leancloud_visitors" data-flag-title="SSM(十八) 秒杀架构实践">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2019/05/08/5cd1d713e19ed.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>之前在 <a href="https://github.com/crossoverJie/Java-Interview/blob/master/MD/Spike.md">Java-Interview</a> 中提到过秒杀架构的设计，这次基于其中的理论简单实现了一下。</p>
<blockquote>
<p>本次采用循序渐进的方式逐步提高性能达到并发秒杀的效果，文章较长请准备好瓜子板凳(liushuizhang😂)。</p>
</blockquote>
<p>本文所有涉及的代码：</p>
<ul>
<li><a href="https://github.com/crossoverJie/SSM">https://github.com/crossoverJie/SSM</a></li>
<li><a href="https://github.com/crossoverJie/distributed-redis-tool">https://github.com/crossoverJie/distributed-redis-tool</a></li>
</ul>
<p>最终架构图：</p>
<p><img src="https://i.loli.net/2018/05/08/5af079ea8618b.png" alt="系统架构设计.png"></p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/05/07/ssm/SSM18-seconds-kill/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/04/28/sbc/sbc7-Distributed-Limit/" itemprop="url">
                  sbc(七)分布式限流
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-04-28T01:03:12+08:00" content="2018-04-28">
              2018-04-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/sbc/" itemprop="url" rel="index">
                    <span itemprop="name">sbc</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/sbc/Distributed-Tools/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed Tools</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/04/28/sbc/sbc7-Distributed-Limit/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/04/28/sbc/sbc7-Distributed-Limit/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/04/28/sbc/sbc7-Distributed-Limit/" class="leancloud_visitors" data-flag-title="sbc(七)分布式限流">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2019/05/08/5cd1d53453d1c.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>本文接着上文<a href="http://crossoverjie.top/2017/08/11/sbc4/">应用限流</a>进行讨论。</p>
<p>之前谈到的限流方案只能针对于单个 JVM 有效，也就是单机应用。而对于现在普遍的分布式应用也得有一个分布式限流的方案。</p>
<p>基于此尝试写了这个组件：</p>
<p><a href="https://github.com/crossoverJie/distributed-redis-tool">https://github.com/crossoverJie/distributed-redis-tool</a></p>
<h2 id="DEMO"><a href="#DEMO" class="headerlink" title="DEMO"></a>DEMO</h2><p>以下采用的是</p>
<p><a href="https://github.com/crossoverJie/springboot-cloud">https://github.com/crossoverJie/springboot-cloud</a></p>
<p>来做演示。</p>
<p>在 Order 应用提供的接口中采取了限流。首先是配置了限流工具的 Bean:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisLimitConfig</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;redis.limit&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> limit;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> JedisConnectionFactory jedisConnectionFactory;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> RedisLimit <span class="title">build</span><span class="params">()</span> </span>&#123;</div><div class="line">        RedisClusterConnection clusterConnection = jedisConnectionFactory.getClusterConnection();</div><div class="line">        JedisCluster jedisCluster = (JedisCluster) clusterConnection.getNativeConnection();</div><div class="line">        RedisLimit redisLimit = <span class="keyword">new</span> RedisLimit.Builder&lt;&gt;(jedisCluster)</div><div class="line">                .limit(limit)</div><div class="line">                .build();</div><div class="line"></div><div class="line">        <span class="keyword">return</span> redisLimit;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接着在 Controller 使用组件：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Autowired</span></div><div class="line"><span class="keyword">private</span> RedisLimit redisLimit ;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="meta">@CheckReqNo</span></div><div class="line"><span class="function"><span class="keyword">public</span> BaseResponse&lt;OrderNoResVO&gt; <span class="title">getOrderNo</span><span class="params">(@RequestBody OrderNoReqVO orderNoReq)</span> </span>&#123;</div><div class="line">    BaseResponse&lt;OrderNoResVO&gt; res = <span class="keyword">new</span> BaseResponse();</div><div class="line"></div><div class="line">    <span class="comment">//限流</span></div><div class="line">    <span class="keyword">boolean</span> limit = redisLimit.limit();</div><div class="line">    <span class="keyword">if</span> (!limit)&#123;</div><div class="line">        res.setCode(StatusEnum.REQUEST_LIMIT.getCode());</div><div class="line">        res.setMessage(StatusEnum.REQUEST_LIMIT.getMessage());</div><div class="line">        <span class="keyword">return</span> res ;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    res.setReqNo(orderNoReq.getReqNo());</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == orderNoReq.getAppId())&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> SBCException(StatusEnum.FAIL);</div><div class="line">    &#125;</div><div class="line">    OrderNoResVO orderNoRes = <span class="keyword">new</span> OrderNoResVO() ;</div><div class="line">    orderNoRes.setOrderId(DateUtil.getLongTime());</div><div class="line">    res.setCode(StatusEnum.SUCCESS.getCode());</div><div class="line">    res.setMessage(StatusEnum.SUCCESS.getMessage());</div><div class="line">    res.setDataBody(orderNoRes);</div><div class="line">    <span class="keyword">return</span> res ;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>为了方便使用，也提供了注解:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="meta">@ControllerLimit</span></div><div class="line"><span class="function"><span class="keyword">public</span> BaseResponse&lt;OrderNoResVO&gt; <span class="title">getOrderNoLimit</span><span class="params">(@RequestBody OrderNoReqVO orderNoReq)</span> </span>&#123;</div><div class="line">    BaseResponse&lt;OrderNoResVO&gt; res = <span class="keyword">new</span> BaseResponse();</div><div class="line">    <span class="comment">// 业务逻辑</span></div><div class="line">    <span class="keyword">return</span> res ;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>该注解拦截了 http 请求，会再请求达到阈值时直接返回。</p>
<p>普通方法也可使用:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@CommonLimit</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span></span>&#123;&#125;</div></pre></td></tr></table></figure>
<p>会在调用达到阈值时抛出异常。</p>
<p>为了模拟并发，在 <a href="https://github.com/crossoverJie/springboot-cloud/blob/master/sbc-user/user/src/main/java/com/crossoverJie/sbcuser/controller/UserController.java#L72-L91">User</a> 应用中开启了 10 个线程调用 Order(<strong>限流次数为5</strong>) 接口(也可使用专业的并发测试工具 JMeter 等)。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/04/28/sbc/sbc7-Distributed-Limit/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/04/12/translation/translation-What Is The Best Programming Language to Start/" itemprop="url">
                  【译】对于初学者什么是最好的编程语言？
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-04-12T01:02:13+08:00" content="2018-04-12">
              2018-04-12
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/翻译/" itemprop="url" rel="index">
                    <span itemprop="name">翻译</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/04/12/translation/translation-What Is The Best Programming Language to Start/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/04/12/translation/translation-What Is The Best Programming Language to Start/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/04/12/translation/translation-What Is The Best Programming Language to Start/" class="leancloud_visitors" data-flag-title="【译】对于初学者什么是最好的编程语言？">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <h3 id="原文链接"><a href="#原文链接" class="headerlink" title="原文链接"></a><a href="https://hackernoon.com/what-is-the-best-programming-language-to-start-8ca8fb5e9a60">原文链接</a></h3><p>Python？Java？Ruby？JavaScript？有非常多的选择。选择一种编程语言开始你的编码之旅不应该是一件艰巨的任务。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d7b300f5c.jpg" alt=""></p>
<p>事实上：你将要学习的语言并不是特别重要，更重要的是学习编程的理念。对于任何编程语言来说知识的可传递性都是至关重要的。</p>
<p>我学习的第一门语言是 Java，学习了循环，while 循环，条件，函数，面向对象编程和许多编程理念。</p>
<p>然而，选择一门能在编程领域轻松找到工作的语言是更好的选择。对于初学者来说，我这里有一份列表推荐给你：</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/04/12/translation/translation-What Is The Best Programming Language to Start/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/04/07/algorithm/LRU-cache/" itemprop="url">
                  动手实现一个 LRU cache
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-04-07T01:01:36+08:00" content="2018-04-07">
              2018-04-07
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/算法/" itemprop="url" rel="index">
                    <span itemprop="name">算法</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/算法/LRU-cache/" itemprop="url" rel="index">
                    <span itemprop="name">LRU cache</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/04/07/algorithm/LRU-cache/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/04/07/algorithm/LRU-cache/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/04/07/algorithm/LRU-cache/" class="leancloud_visitors" data-flag-title="动手实现一个 LRU cache">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2019/05/08/5cd1d7b5984ac.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>LRU 是 <code>Least Recently Used</code> 的简写，字面意思则是<code>最近最少使用</code>。</p>
<p>通常用于缓存的淘汰策略实现，由于缓存的内存非常宝贵，所以需要根据某种规则来剔除数据保证内存不被撑满。</p>
<p>如常用的 Redis 就有以下几种策略：</p>
<table>
<thead>
<tr>
<th style="text-align:center">策略</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">volatile-lru</td>
<td style="text-align:center">从已设置过期时间的数据集中挑选最近最少使用的数据淘汰</td>
</tr>
<tr>
<td style="text-align:center">volatile-ttl</td>
<td style="text-align:center">从已设置过期时间的数据集中挑选将要过期的数据淘汰</td>
</tr>
<tr>
<td style="text-align:center">volatile-random</td>
<td style="text-align:center">从已设置过期时间的数据集中任意选择数据淘汰</td>
</tr>
<tr>
<td style="text-align:center">allkeys-lru</td>
<td style="text-align:center">从所有数据集中挑选最近最少使用的数据淘汰</td>
</tr>
<tr>
<td style="text-align:center">allkeys-random</td>
<td style="text-align:center">从所有数据集中任意选择数据进行淘汰</td>
</tr>
<tr>
<td style="text-align:center">no-envicition</td>
<td style="text-align:center">禁止驱逐数据</td>
</tr>
</tbody>
</table>
<blockquote>
<p>摘抄自:<a href="https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Redis.md#%E5%8D%81%E4%B8%89%E6%95%B0%E6%8D%AE%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5">https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Redis.md#%E5%8D%81%E4%B8%89%E6%95%B0%E6%8D%AE%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5</a></p>
</blockquote>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/04/07/algorithm/LRU-cache/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/2018/03/29/distributed-lock/distributed-lock-redis/" itemprop="url">
                  基于 Redis 的分布式锁
                </a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-03-29T20:10:36+08:00" content="2018-03-29">
              2018-03-29
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Distributed-Tools/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed Tools</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/03/29/distributed-lock/distributed-lock-redis/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/03/29/distributed-lock/distributed-lock-redis/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/03/29/distributed-lock/distributed-lock-redis/" class="leancloud_visitors" data-flag-title="基于 Redis 的分布式锁">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          <p><img src="https://i.loli.net/2019/05/08/5cd1d7a3c310a.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>分布式锁在分布式应用中应用广泛，想要搞懂一个新事物首先得了解它的由来，这样才能更加的理解甚至可以举一反三。</p>
<p>首先谈到分布式锁自然也就联想到分布式应用。</p>
<p>在我们将应用拆分为分布式应用之前的单机系统中，对一些并发场景读取公共资源时如扣库存，卖车票之类的需求可以简单的使用<a href="http://crossoverjie.top/2018/01/14/Synchronize/">同步</a>或者是<a href="http://crossoverjie.top/2018/01/25/ReentrantLock/">加锁</a>就可以实现。</p>
<p>但是应用分布式了之后系统由以前的单进程多线程的程序变为了多进程多线程，这时使用以上的解决方案明显就不够了。</p>
<p>因此业界常用的解决方案通常是借助于一个第三方组件并利用它自身的排他性来达到多进程的互斥。如：</p>
<ul>
<li>基于 DB 的唯一索引。</li>
<li>基于 ZK 的临时有序节点。</li>
<li>基于 Redis 的 <code>NX EX</code> 参数。</li>
</ul>
<p>这里主要基于 Redis 进行讨论。</p>
          <div class="post-more-link text-center">
            <a class="btn" href="/2018/03/29/distributed-lock/distributed-lock-redis/#more" rel="contents">
              Read more &raquo;
            </a>
          </div>
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/6/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/6/">6</a><span class="page-number current">7</span><a class="page-number" href="/page/8/">8</a><span class="space">&hellip;</span><a class="page-number" href="/page/12/">12</a><a class="extend next" rel="next" href="/page/8/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel  sidebar-panel-active ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = 'page/7/index.html';
      var disqus_title = "";
      var disqus_url = '';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
